package com.dy.yunying.biz.service.hongbao.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.entity.gametask.GameTaskConfig;
import com.dy.yunying.api.entity.hongbao.HbReceivingRecord;
import com.dy.yunying.api.enums.HbCurrencyTypeEnum;
import com.dy.yunying.api.enums.HbVoucherTypeEnum;
import com.dy.yunying.api.resp.hongbao.CashExportVo;
import com.dy.yunying.api.resp.hongbao.RedPackExportVo;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.dao.ads.gametask.GameTaskConfigMapper;
import com.dy.yunying.biz.dao.ads.hongbao.HbActivityGameMapper;
import com.dy.yunying.biz.service.hongbao.HbReceivingRecordService;
import com.dy.yunying.biz.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.dto.hongbao.HbRedpackConfigDto;
import com.dy.yunying.api.entity.hongbao.HbGiftBag;
import com.dy.yunying.api.entity.hongbao.HbRedpackConfig;
import com.dy.yunying.api.enums.HbConditionTypeEnum;
import com.dy.yunying.api.enums.HbRedpackTypeEnum;
import com.dy.yunying.api.utils.CheckUtils;
import com.dy.yunying.api.utils.FileUtils;
import com.dy.yunying.api.vo.hongbao.HbRedpackConfigVo;
import com.dy.yunying.biz.dao.ads.hongbao.HbRedpackConfigMapper;
import com.dy.yunying.biz.service.hongbao.ActivityService;
import com.dy.yunying.biz.service.hongbao.HbGiftBagService;
import com.dy.yunying.biz.service.hongbao.HbRedpackConfigService;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.common.core.mybatis.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 红包配置表
 * @author  chenxiang
 * @version  2021-10-25 14:19:00
 * table: hb_redpack_config
 */
@Log4j2
@Service("hbRedpackConfigService")
@RequiredArgsConstructor
public class HbRedpackConfigServiceImpl extends ServiceImpl<HbRedpackConfigMapper, HbRedpackConfig> implements HbRedpackConfigService {

	private final HbRedpackConfigMapper hbRedpackConfigMapper;

	private final HbGiftBagService hbGiftBagService;

	private final ActivityService activityService;

	private final HbActivityGameMapper activityGameMapper;

	private final HbReceivingRecordService hbReceivingRecordService;

	private final GameTaskConfigMapper gameTaskConfigMapper;

	@Resource
	private YunYingProperties yunYingProperties;

	/**
	 * 红包列表
	 * @param vo
	 * @return
	 */
	@Override
	public R getPage(HbRedpackConfigVo vo){
		Page page = new Page();
		page.setCurrent(vo.getCurrent());
		page.setSize(vo.getSize());
		QueryWrapper<HbRedpackConfig> wrapper = new QueryWrapper<>();
		wrapper.eq("activity_id",vo.getActivityId());
		if (StringUtils.isNotBlank(vo.getType())){
			wrapper.eq("type",vo.getType());
		}
		wrapper.eq("status",1);
		wrapper.eq("deleted",0);
		wrapper.orderByAsc("sort","id");
		IPage<HbRedpackConfig> iPage = this.page(page,wrapper);
		return R.ok(iPage);
	}
	/**
	 * 添加红包
	 * @param vo
	 * @return
	 */
	@Override
	@Transactional(value = "adsTransactionManager", rollbackFor = Exception.class)
	public R addEditRedPack(HbRedpackConfigVo vo){
		HbRedpackConfig redpackConfig = new HbRedpackConfig();
		R result = checkParam(vo,redpackConfig);
		if (0 != result.getCode()){
			return result;
		}
		redpackConfig.setMoney(new BigDecimal(vo.getMoney()));
		redpackConfig.setType(Integer.valueOf(vo.getType()));
		redpackConfig.setConditionType(Integer.valueOf(vo.getConditionType()));
		redpackConfig.setName(vo.getName());
		redpackConfig.setTitle(vo.getTitle());
		redpackConfig.setCashValues(new BigDecimal(vo.getCashValues()));
		redpackConfig.setUseAmount(Integer.valueOf(vo.getUseAmount()));
		redpackConfig.setAngleMark(Integer.valueOf(vo.getAngleMark()));
		redpackConfig.setDetailsStatus(Integer.valueOf(vo.getDetailsStatus()));
		redpackConfig.setUseAmount(Integer.valueOf(vo.getUseAmount()));
		redpackConfig.setSort(Integer.valueOf(vo.getSort()));
		redpackConfig.setIconUrl(StringUtils.equals(vo.getIconUrl(),"null") ? "" : vo.getIconUrl());
		redpackConfig.setAmountShow(StringUtils.isNotBlank(vo.getAmountShow()) ? Integer.valueOf(vo.getAmountShow()) : 0);
		redpackConfig.setAutoReceive(vo.getAutoReceive() == null ? 2 : vo.getAutoReceive());
		if (null != vo.getCdkLimitType()) {
			redpackConfig.setCdkLimitType(vo.getCdkLimitType());
		}
		if (HbRedpackTypeEnum.GIFT.getType().equals(vo.getType())) {
			//判断活动范围是否有多个父游戏
			List<Long> pGameList = activityGameMapper.selectGroupPgIdByActivityId(redpackConfig.getActivityId());
			if (CollectionUtils.isNotEmpty(pGameList) && pGameList.size() > 1) {
				return R.failed("多个父游戏时，不能选择礼包码");
			}
			if (StringUtils.isBlank(vo.getId())){
				redpackConfig.setGiftAmount(StringUtils.isBlank(vo.getGiftAmount())?0:Integer.valueOf(vo.getGiftAmount()));
			}
		}else{
			redpackConfig.setGiftAmount(StringUtils.isBlank(vo.getGiftAmount())?-1:Integer.valueOf(vo.getGiftAmount()));
		}
		//游戏任务，不能是多游戏
		String conditionTaskId = vo.getConditionTaskId();
		if (StringUtils.isNotBlank(conditionTaskId)){
			//判断活动范围是否有多个父游戏
			List<Long> pGameList = activityGameMapper.selectGroupPgIdByActivityId(Long.valueOf(vo.getActivityId()));
			if (CollectionUtils.isNotEmpty(pGameList) && pGameList.size() > 1) {
				return R.failed("多个父游戏时，不能选择游戏任务");
			}
			//修改的时候,从数据库获取名称
			if (StringUtils.isNotBlank(vo.getId())){
				if(CollectionUtils.isNotEmpty(pGameList)){
					log.info(" pGameid:{}, conditionTaskId:{}", pGameList.get(0), conditionTaskId);
					GameTaskConfig gameTaskConfig =gameTaskConfigMapper.selectOne(new QueryWrapper<GameTaskConfig>().lambda().eq(GameTaskConfig::getParentGameId, pGameList.get(0)).eq(GameTaskConfig::getTaskId, conditionTaskId).last(" limit 1"));
					log.info(" gameTaskConfig:{}",gameTaskConfig);
					if(gameTaskConfig != null && StringUtils.isNotBlank(gameTaskConfig.getTaskDescription())){
						redpackConfig.setTitle(gameTaskConfig.getTaskDescription());
					}
				}
			}
		}

		boolean flag = false;
		if (StringUtils.isBlank(vo.getId())){
			redpackConfig.setCreateTime(new Date());
			redpackConfig.setUpdateTime(new Date());
			redpackConfig.setCreateId(Long.valueOf(SecurityUtils.getUser().getId()));
			flag = this.save(redpackConfig);
		} else {
			redpackConfig.setId(Long.valueOf(vo.getId()));
			redpackConfig.setUpdateTime(new Date());
			redpackConfig.setUpdateId(Long.valueOf(SecurityUtils.getUser().getId()));
			flag = this.updateById(redpackConfig);
		}
		if (flag){
			HbRedpackConfig resultRedpackConfig = this.getById(redpackConfig.getId());
			// 更新活动奖池
			activityService.sumActivity(resultRedpackConfig.getActivityId());
			// 上传礼包码
			if (HbRedpackTypeEnum.GIFT.getType().equals(String.valueOf(redpackConfig.getType()))){
				if (1 == redpackConfig.getGiftType().intValue()){
					// 添加礼包码
					R resultGift = addGiftBag(vo,resultRedpackConfig);
					if (0 == resultGift.getCode()){
						return R.ok(resultRedpackConfig,resultGift.getMsg());
					}else{
						throw new RuntimeException(resultGift.getMsg());
					}
				}else if(2 == redpackConfig.getGiftType().intValue()){
					// 通用礼包码
					addCommonGift(resultRedpackConfig);
				}
			}
			return R.ok(resultRedpackConfig);
		}
		return R.failed();
	}
	/**
	 * 删除红包
	 * @param vo
	 * @return
	 */
	@Override
	public R delRedPack(HbRedpackConfigVo vo){
		HbRedpackConfig hbRedpackConfig = this.getById(vo.getId());
		if (Objects.isNull(hbRedpackConfig)){
			return R.failed("红包ID无效");
		}
		HbRedpackConfig redpackConfig = new HbRedpackConfig();
		redpackConfig.setId(Long.valueOf(vo.getId()));
		redpackConfig.setDeleted(1);
		redpackConfig.setUpdateId(Long.valueOf(SecurityUtils.getUser().getId()));
		redpackConfig.setUpdateTime(new Date());
		boolean flag = this.updateById(redpackConfig);
		if (flag){
			// 更新活动奖池
			activityService.sumActivity(hbRedpackConfig.getActivityId());
			return R.ok();
		}
		return R.failed();
	}
	/**
	 * 统计活动现金价值
	 * @param vo
	 * @return
	 */
	@Override
	public R getCashValues(HbRedpackConfigVo vo){
		QueryWrapper<HbRedpackConfig> wrapper = new QueryWrapper<>();
		wrapper.select("type","SUM(cash_values * IF(gift_amount = -1,1,gift_amount)) as cash_values");
		wrapper.eq("deleted",0);
		wrapper.eq("status",1);
		wrapper.eq("activity_id",vo.getActivityId());
		wrapper.isNotNull("type");
		wrapper.groupBy("type");
		List<HbRedpackConfig> redpackConfigList = this.list(wrapper);
		BigDecimal init = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);
		HashMap<String,BigDecimal> resultMap = new HashMap<String,BigDecimal>(){
			{
				put("totalValues",init);
				put("cashValues",init);
				put("giftValues",init);
				put("goodsValues",init);
				put("voucherValues",init);
				put("balanceValues",init);
			}
		};
		if (CollectionUtils.isNotEmpty(redpackConfigList) && redpackConfigList.size() > 0){
			BigDecimal totalValues = new BigDecimal(0);
			for (HbRedpackConfig redpackConfig : redpackConfigList){
				if (StringUtils.equals(HbRedpackTypeEnum.CASH.getType(),String.valueOf(redpackConfig.getType()))){
					resultMap.put("cashValues",redpackConfig.getCashValues().setScale(2, BigDecimal.ROUND_HALF_UP));
				}else if(StringUtils.equals(HbRedpackTypeEnum.GIFT.getType(),String.valueOf(redpackConfig.getType()))){
					resultMap.put("giftValues",redpackConfig.getCashValues().setScale(2, BigDecimal.ROUND_HALF_UP));
				}else if(StringUtils.equals(HbRedpackTypeEnum.GOODS.getType(),String.valueOf(redpackConfig.getType()))){
					resultMap.put("goodsValues",redpackConfig.getCashValues().setScale(2, BigDecimal.ROUND_HALF_UP));
				}else if(StringUtils.equals(HbRedpackTypeEnum.VOUCHER.getType(),String.valueOf(redpackConfig.getType()))){
					resultMap.put("voucherValues",redpackConfig.getCashValues().setScale(2, BigDecimal.ROUND_HALF_UP));
				}else if(StringUtils.equals(HbRedpackTypeEnum.BALANCE.getType(),String.valueOf(redpackConfig.getType()))){
					resultMap.put("balanceValues",redpackConfig.getCashValues().setScale(2, BigDecimal.ROUND_HALF_UP));
				}
				totalValues = totalValues.add(redpackConfig.getCashValues());
			}
			resultMap.put("totalValues",totalValues.setScale(2, BigDecimal.ROUND_HALF_UP));
		}
		return R.ok(resultMap);
	}

	/**
	 * 更新通用礼包码信息
	 * @param redpackConfig
	 * @return
	 */
	public R addCommonGift(HbRedpackConfig redpackConfig){
		int count = hbReceivingRecordService.count(Wrappers.<HbReceivingRecord>lambdaQuery()
				.eq(HbReceivingRecord::getActivityId,redpackConfig.getActivityId())
				.eq(HbReceivingRecord::getObjectType,1)
				.eq(HbReceivingRecord::getObjectId,redpackConfig.getId())
				.eq(HbReceivingRecord::getType,HbRedpackTypeEnum.GIFT.getType())
				.eq(HbReceivingRecord::getGiftCode,redpackConfig.getGiftCode()));

		HbGiftBag hbGiftBag = hbGiftBagService.getOne(Wrappers.<HbGiftBag>lambdaQuery()
				.eq(HbGiftBag::getType,1)
				.eq(HbGiftBag::getObjectId,redpackConfig.getId())
				.eq(HbGiftBag::getGiftCode,redpackConfig.getGiftCode())
				.last("limit 1")
		);

		if (Objects.isNull(hbGiftBag)) {
			HbGiftBag giftBag = new HbGiftBag();
			giftBag.setType(1);
			giftBag.setObjectId(redpackConfig.getId());
			giftBag.setGiftCode(redpackConfig.getGiftCode());
			giftBag.setGiftAmount(redpackConfig.getGiftAmount());
			giftBag.setGiftGetcounts(count);
			giftBag.setUsable(2);
			giftBag.setCreateTime(new Date());
			giftBag.setUpdateTime(new Date());
			giftBag.setCreateId(Long.valueOf(SecurityUtils.getUser().getId()));
			hbGiftBagService.save(giftBag);
		}else{
			HbGiftBag updateGift = new HbGiftBag();
			updateGift.setId(hbGiftBag.getId());
			updateGift.setGiftAmount(redpackConfig.getGiftAmount());
			updateGift.setGiftGetcounts(count);
			updateGift.setDeleted(0);
			hbGiftBagService.updateById(updateGift);
		}
		// 更新红包礼包码已领取数量
		HbRedpackConfig upConfig = new HbRedpackConfig();
		upConfig.setId(redpackConfig.getId());
		upConfig.setGiftGetcounts(count);
		this.updateById(upConfig);

		return R.ok(redpackConfig);
	}
	/**
	 * 添加礼包码
	 * @param vo
	 * @param redpackConfig
	 */
	public R addGiftBag(HbRedpackConfigVo vo,HbRedpackConfig redpackConfig){
		String msg = "操作成功";
		if (Objects.nonNull(vo.getFile())) {
			List<String> listData = FileUtils.readFileContent(vo.getFile());
			if (CollectionUtils.isNotEmpty(listData)) {
				String regex = "^[A-Za-z0-9]+$";
				List<String> listDistinct = listData.stream().distinct().collect(Collectors.toList());
				List<String> list = listDistinct.stream().filter(item -> item.length() >= 3 && item.length() <= 50 && item.matches(regex)).collect(Collectors.toList());
				List<HbGiftBag> giftBagList = Lists.newArrayList();
				if (CollectionUtils.isNotEmpty(list)) {
					QueryWrapper<HbGiftBag> wrapper = new QueryWrapper<>();
					wrapper.in("gift_code", list);
					wrapper.eq("deleted",0);
					List<HbGiftBag> resultList = hbGiftBagService.list(wrapper);

					for (String str : list) {
						if (StringUtils.isNotBlank(str) && str.length() > 0) {
							String code = str.trim();
							if (CollectionUtils.isNotEmpty(resultList)) {
								int num = resultList.stream().filter(item -> code.equals(item.getGiftCode())).collect(Collectors.toList()).size();
								if (num > 0) {
									continue;
								}
							}
							HbGiftBag giftBag = new HbGiftBag();
							giftBag.setType(1);
							giftBag.setObjectId(redpackConfig.getId());
							giftBag.setGiftCode(code);
							giftBag.setCreateTime(new Date());
							giftBag.setUpdateTime(new Date());
							giftBag.setCreateId(Long.valueOf(SecurityUtils.getUser().getId()));
							giftBagList.add(giftBag);
						}
					}
					if (CollectionUtils.isNotEmpty(giftBagList)) {
						hbGiftBagService.saveBatch(giftBagList);
						// 更新红包礼包码数量
						HbRedpackConfig upConfig = new HbRedpackConfig();
						upConfig.setId(redpackConfig.getId());
						upConfig.setGiftAmount(redpackConfig.getGiftAmount() + giftBagList.size());
						this.updateById(upConfig);
					}
				}
				int giftBagSize = giftBagList.size();
				msg = "操作成功，礼包码上传成功："+ giftBagSize +"个，重复无效过滤："+ (listData.size() - giftBagSize) +"个";
			}
		}
		return R.ok(0,msg);
	}
	/**
	 * 红包详情
	 * @param vo
	 * @return
	 */
	@Override
	public R details(HbRedpackConfigVo vo){
		HbRedpackConfigDto redpackConfig = hbRedpackConfigMapper.selectRedpackConfigById(vo.getId());
		return R.ok(redpackConfig);
	}
	/**
	 * 验证参数
	 * @param vo
	 * @param redpackConfig
	 * @return
	 */
	public R checkParam(HbRedpackConfigVo vo,HbRedpackConfig redpackConfig){
		Date now = new Date();
		String type = String.valueOf(vo.getType());
		String conditionType = String.valueOf(vo.getConditionType());
		String voucherType = vo.getVoucherType();//有效规则
		String currencyAmount = vo.getCurrencyAmount();//游豆
		if (StringUtils.isBlank(vo.getId())){
			if (StringUtils.isBlank(vo.getActivityId())){
				return R.failed("活动ID不能为空");
			}
			redpackConfig.setActivityId(Long.valueOf(vo.getActivityId()));
		}
		if (StringUtils.isBlank(type)){
			return R.failed("红包类型不能为空");
		}
		if (StringUtils.isBlank(conditionType)){
			return R.failed("条件类型不能为空");
		}
		if (StringUtils.isBlank(HbConditionTypeEnum.getName(conditionType))){
			return R.failed("未知领取条件类型");
		}
		if (HbConditionTypeEnum.Condition1.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition2.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition9.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition15.getType().equals(conditionType)){
			// 角色等级
			String conditionRoleLevel = vo.getConditionRoleLevel();
			if (StringUtils.isBlank(conditionRoleLevel)){
				return R.failed("请输入角色等级");
			}
			if (!CheckUtils.checkInt(conditionRoleLevel)){
				return R.failed("请输入有效的角色等级");
			}
			if (conditionRoleLevel.length() > 6 || Integer.valueOf(conditionRoleLevel) < 1 || Integer.valueOf(conditionRoleLevel) > 999999){
				return R.failed("角色等级应为1~999999");
			}
			redpackConfig.setConditionRoleLevel(Integer.valueOf(conditionRoleLevel));
		}

		//角色连续登录N天
		if(HbConditionTypeEnum.Condition12.getType().equals(conditionType)){
			String conditionRoleDays = vo.getConditionRoleDays();
			if (StringUtils.isBlank(conditionRoleDays)){
				return R.failed("请输入角色连续登录天数");
			}
			if (!CheckUtils.checkInt(conditionRoleDays)){
				return R.failed("请输入有效的角色连续登录天数");
			}
			if (conditionRoleDays.length() > 4 || Integer.valueOf(conditionRoleDays) < 1 || Integer.valueOf(conditionRoleDays) > 365){
				return R.failed("角色连续登录天数应为1~365");
			}
			redpackConfig.setConditionRoleDays(Integer.valueOf(conditionRoleDays));
		}


		//角色累计登录N天
		if(HbConditionTypeEnum.Condition19.getType().equals(conditionType)){
			String conditionRoleDays = vo.getConditionRoleDays();
			if (StringUtils.isBlank(conditionRoleDays)){
				return R.failed("请输入角色累计登录天数");
			}
			if (!CheckUtils.checkInt(conditionRoleDays)){
				return R.failed("请输入有效的角色累计登录天数");
			}
			if (conditionRoleDays.length() > 4 || Integer.valueOf(conditionRoleDays) < 1 || Integer.valueOf(conditionRoleDays) > 365){
				return R.failed("角色累计登录天数应为1~365");
			}
			redpackConfig.setConditionRoleDays(Integer.valueOf(conditionRoleDays));
		}


		if (HbConditionTypeEnum.Condition2.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition9.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition13.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition14.getType().equals(conditionType)){
			// 创角天数
			String conditionRoleDays = vo.getConditionRoleDays();
			if (StringUtils.isBlank(conditionRoleDays)){
				return R.failed("请输入创角天数");
			}
			if (!CheckUtils.checkInt(conditionRoleDays)){
				return R.failed("请输入有效的创角天数");
			}
			if (conditionRoleDays.length() > 4 || Integer.valueOf(conditionRoleDays) < 1 || Integer.valueOf(conditionRoleDays) > 365){
				return R.failed("创角天数应为1~365");
			}
			redpackConfig.setConditionRoleDays(Integer.valueOf(conditionRoleDays));
		}

		if (HbConditionTypeEnum.Condition15.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition16.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition17.getType().equals(conditionType)){
			// 创角天数
			String conditionRoleDays = vo.getConditionRoleDays();
			if (StringUtils.isBlank(conditionRoleDays)){
				return R.failed("请输入开服天数");
			}
			if (!CheckUtils.checkInt(conditionRoleDays)){
				return R.failed("请输入有效的开服天数");
			}
			if (conditionRoleDays.length() > 4 || Integer.valueOf(conditionRoleDays) < 1 || Integer.valueOf(conditionRoleDays) > 365){
				return R.failed("开服天数应为1~365");
			}
			redpackConfig.setConditionRoleDays(Integer.valueOf(conditionRoleDays));
		}

		if (HbConditionTypeEnum.Condition3.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition5.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition8.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition11.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition13.getType().equals(conditionType) ||
				HbConditionTypeEnum.Condition16.getType().equals(conditionType)){
			// 累计充值
			String conditionRoleRecharge = vo.getConditionRoleRecharge();
			if (StringUtils.isBlank(conditionRoleRecharge)){
				return R.failed("请输入充值金额");
			}
			if (!CheckUtils.checkMoney(conditionRoleRecharge)){
				return R.failed("请输入有效的充值金额");
			}
			if (conditionRoleRecharge.length() > 7 || Integer.valueOf(conditionRoleRecharge) < 1 || Integer.valueOf(conditionRoleRecharge) > 9999999){
				return R.failed("充值金额应为1~9999999");
			}
			redpackConfig.setConditionRoleRecharge(new BigDecimal(conditionRoleRecharge));
		}
		//游戏任务
		if (HbConditionTypeEnum.Condition18.getType().equals(conditionType)){
			// 游戏任务ID
			String conditionTaskId = vo.getConditionTaskId();
			if (StringUtils.isBlank(conditionTaskId)){
				return R.failed("请选择游戏任务");
			}
			redpackConfig.setConditionTaskId(Long.valueOf(conditionTaskId));
		}



		String money = vo.getMoney();
		if (StringUtils.isBlank(money)){
			return R.failed("请输入红包金额");
		}
		if (!CheckUtils.checkMoney(money)){
			return R.failed("请输入有效的红包金额");
		}
		if (new BigDecimal(money).compareTo(BigDecimal.ZERO) < 0 || new BigDecimal(money).compareTo(new BigDecimal("9999999")) > 0){
			return R.failed("红包金额应大于0，小于9999999");
		}

		if (HbRedpackTypeEnum.CASH.getType().equals(type)){
			//
		}else if (HbRedpackTypeEnum.GIFT.getType().equals(type)){
			if (StringUtils.isBlank(vo.getGiftType())){
				return R.failed("请选择礼包码类型");
			}
			redpackConfig.setGiftType(Integer.valueOf(vo.getGiftType()));
			// 礼包码为唯一码
			if (1 == Integer.valueOf(vo.getGiftType()).intValue()) {
				if (StringUtils.isBlank(vo.getId()) && Objects.isNull(vo.getFile())) {
					return R.failed("请上传礼包码(txt文件)");
				}
				if (Objects.nonNull(vo.getFile())) {
					MultipartFile file = vo.getFile();
					Long size = file.getSize();
					if (size < 3 || size > 1048576) {
						return R.failed("礼包码文件大小应在3字节~1M之间");
					}
					// 获取名称
					String filename = file.getOriginalFilename();
					// 获取后缀名
					String suffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
					if (!"txt".equals(suffix)) {
						return R.failed("请上传txt格式的礼包码文件");
					}
				}
			}else if(2 == Integer.valueOf(vo.getGiftType()).intValue()){
			// 礼包码为通用码
				String giftCode = vo.getGiftCode();
				if (StringUtils.isBlank(giftCode)){
					return R.failed("请输入通用礼包码");
				}
				String regex = "^[A-Za-z0-9]+$";
				if (giftCode.length() < 3 || giftCode.length() > 50 || !giftCode.matches(regex)){
					return R.failed("通用礼包码应为3~50个英文大小写或数字组成");
				}
				redpackConfig.setGiftCode(giftCode);
				String giftAmount = vo.getGiftAmount();
				if (StringUtils.isBlank(giftAmount)){
					return R.failed("请输入礼包码数量");
				}
				if (!CheckUtils.checkInt(giftAmount)){
					return R.failed("请输入有效的礼包数量");
				}
				if (giftAmount.length() > 7 || Integer.valueOf(giftAmount) < 0 || Integer.valueOf(giftAmount) > 9999999){
					return R.failed("礼包数量应为0~9999999");
				}
				redpackConfig.setGiftAmount(Integer.valueOf(giftAmount));
			}
		}else if (HbRedpackTypeEnum.GOODS.getType().equals(type)){
//			if (StringUtils.isBlank(vo.getGiftAmount())){
//				return R.failed("请输入实物礼品总数量");
//			}
		}else if (HbRedpackTypeEnum.VOUCHER.getType().equals(type)){
			String limitMoney = vo.getLimitMoney();
			if (StringUtils.isNotBlank(limitMoney)){
				if (!CheckUtils.checkMoney(limitMoney)){
					return R.failed("请输入有效的满可用金额");
				}
				if (limitMoney.length() > 7 || Integer.valueOf(limitMoney) < 1 || Integer.valueOf(limitMoney) > 9999999){
					return R.failed("代金券满可用金额应为1~9999999");
				}
				redpackConfig.setLimitMoney(new BigDecimal(limitMoney));
			}
			if (Integer.valueOf(money).intValue() >= Integer.valueOf(limitMoney).intValue()){
				return R.failed("代金券金额必须小于满可用金额");
			}

			if (StringUtils.isBlank(voucherType)){
				return R.failed("代金券有效期不能为空");
			}
			redpackConfig.setVoucherType(Integer.valueOf(voucherType));
			if (HbVoucherTypeEnum.FIXED.getType().equals(voucherType)){
				if (StringUtils.isBlank(vo.getVoucherStartTime())){
					return R.failed("代金券有效开始时间不能为空");
				}
				if (StringUtils.isBlank(vo.getVoucherEndTime())){
					return R.failed("代金券有效结束时间不能为空");
				}
				redpackConfig.setVoucherStartTime(DateUtils.stringToDate(vo.getVoucherStartTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
				redpackConfig.setVoucherEndTime(DateUtils.stringToDate(vo.getVoucherEndTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
			}else if (HbVoucherTypeEnum.APPOINT.getType().equals(voucherType)){
				String voucherDays = vo.getVoucherDays();
				if (StringUtils.isBlank(voucherDays)){
					return R.failed("代金券有效天数不能为空");
				}
				if (voucherDays.length() > 4 || Integer.valueOf(voucherDays) < 1 || Integer.valueOf(voucherDays) > 365){
					return R.failed("代金券有效天数应为1~365");
				}
				redpackConfig.setVoucherDays(Integer.valueOf(vo.getVoucherDays()));
			}
			if (null == vo.getCdkLimitType()) {
				return R.failed("代金券使用限制不能为空");
			}
		}else if (HbRedpackTypeEnum.BALANCE.getType().equals(type)){



			if (StringUtils.isBlank(voucherType)){
				return R.failed("有效规则不能为空");
			}


			if (StringUtils.isBlank(currencyAmount)){
				return R.failed("请输入游豆");
			}
			if (!CheckUtils.checkMoney(currencyAmount)){
				return R.failed("请输入有效的游豆");
			}
			if (currencyAmount.length() > 7 || Integer.valueOf(currencyAmount) < 1 || Integer.valueOf(currencyAmount) > 9999999){
				return R.failed("游豆应为1~9999999");
			}
			redpackConfig.setCurrencyAmount(new BigDecimal(currencyAmount));

			//游豆种类
			Integer currencyType = vo.getCurrencyType();
			if (currencyType == null){
				return R.failed("游豆种类不能为空");
			}
			redpackConfig.setCurrencyType(currencyType);
			switch (HbCurrencyTypeEnum.getOneByType(currencyType)){
				case COMMON : //普通余额
					//有效规则必须为永久
					if(!HbVoucherTypeEnum.PERMANENT.getType().equals(voucherType)){
						return R.failed("有效规则必须是永久");
					}
					break;
				case TEMP: //临时余额
					//固定日期
					if (HbVoucherTypeEnum.FIXED.getType().equals(voucherType)){
						if (StringUtils.isBlank(vo.getVoucherEndTime())){
							return R.failed("临时游豆有效结束时间不能为空");
						}
						vo.setVoucherStartTime(DateUtils.dateToString(now, DateUtils.YYYY_MM_DD_HH_MM_SS));
						redpackConfig.setVoucherStartTime(DateUtils.stringToDate(vo.getVoucherStartTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
						redpackConfig.setVoucherEndTime(DateUtils.stringToDate(vo.getVoucherEndTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
					//领取之后指定天数
					}else if (HbVoucherTypeEnum.APPOINT.getType().equals(voucherType)){
						String voucherDays = vo.getVoucherDays();
						if (StringUtils.isBlank(voucherDays)){
							return R.failed("临时游豆有效天数不能为空");
						}
						if (voucherDays.length() > 4 || Integer.valueOf(voucherDays) < 1 || Integer.valueOf(voucherDays) > 365){
							return R.failed("临时游豆有效天数应为1~365");
						}
						redpackConfig.setVoucherDays(Integer.valueOf(vo.getVoucherDays()));
					}
				break;
				default:
					return R.failed("未知游豆种类");
			}

			redpackConfig.setVoucherType(Integer.valueOf(voucherType));
		}
		String cashValues = vo.getCashValues();
		if (StringUtils.isBlank(cashValues)){
			return R.failed("请输入红包价值金额");
		}
		if (!CheckUtils.checkMoney(cashValues)){
			return R.failed("请输入有效的红包价值金额");
		}
		if (new BigDecimal(cashValues).compareTo(BigDecimal.ZERO) < 0 || new BigDecimal(cashValues).compareTo(new BigDecimal("9999999")) > 0){
			return R.failed("红包价值金额大于0，小于9999999");
		}
		if (StringUtils.isBlank(vo.getName())){
			return R.failed("请输入红包名称");
		}
		if (vo.getName().length() > 20){
			return R.failed("请输入1~20个字符的红包名称");
		}
		if (StringUtils.isBlank(vo.getTitle())){
			return R.failed("请输入红包标题");
		}
		if (vo.getTitle().length() > 50){
			return R.failed("请输入1~50个字符的红包标题");
		}
		String useAmount = vo.getUseAmount();
		if (StringUtils.isBlank(useAmount)){
			return R.failed("请输入单人领取次数");
		}
		if (!CheckUtils.checkInt(useAmount)){
			return R.failed("请输入有效的单人领取次数");
		}
		if (useAmount.length() > 3 || Integer.valueOf(useAmount) < 1 || Integer.valueOf(useAmount) > 99){
			return R.failed("单人领取次数应为1~99");
		}
		if (StringUtils.isBlank(vo.getAngleMark())){
			return R.failed("请选择推荐角标");
		}
		if (StringUtils.isBlank(vo.getDetailsStatus())){
			return R.failed("请选择红包详情状态");
		}
		if (StringUtils.equals("1",vo.getDetailsStatus())){
			if (StringUtils.isBlank(vo.getDetails())){
				return R.failed("请输入红包详情");
			}
			redpackConfig.setDetails(vo.getDetails());
		}
		if (StringUtils.isNotBlank(vo.getGiftAmount())){
			String giftAmount = vo.getGiftAmount();
			if (!CheckUtils.checkInt(giftAmount)){
				return R.failed("请输入有效的礼包数量");
			}
			if (giftAmount.length() > 7 || Integer.valueOf(giftAmount) < 0 || Integer.valueOf(giftAmount) > 9999999){
				return R.failed("礼包数量应为0~9999999");
			}
		}
		String sort = vo.getSort();
		if (StringUtils.isBlank(sort)){
			return R.failed("请输入排序值");
		}
		if (!CheckUtils.checkInt(sort)){
			return R.failed("请输入正确的排序值");
		}
		if (sort.length() > 8 || Integer.valueOf(sort) < 0 || Integer.valueOf(sort) > 99999999){
			return R.failed("排序值应为0~99999999");
		}
		return R.ok();
	}


	@Override
	public List<RedPackExportVo> export4RedPack(Long activityId) {
		return hbRedpackConfigMapper.exportNoUseGift4RedPack(activityId);
	}

	@Override
	public List<CashExportVo> export4Cash(Long activityId) {
		return hbRedpackConfigMapper.exportNoUseGift4Cash(activityId);
	}

	@Override
	@Transactional(value = "adsTransactionManager", rollbackFor = Exception.class)
	public int updateHasCounts(Long activityId) {
		return hbRedpackConfigMapper.updateHasCounts(activityId);
	}
}


